package com.ternnetwork.core.accesscontroll.service.impl;



import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.ternnetwork.commons.model.http.BaseResponse;
import com.ternnetwork.core.accesscontroll.entity.Department;
import com.ternnetwork.core.accesscontroll.entity.User;
import com.ternnetwork.core.accesscontroll.enums.messages.DepartmentMessages;
import com.ternnetwork.core.accesscontroll.repository.DepartmentRepository;
import com.ternnetwork.core.accesscontroll.service.DepartmentService;
import com.ternnetwork.core.accesscontroll.vo.DepartmentZtree;


@Service
public class DepartmentServiceImpl implements DepartmentService {
	
	 @Autowired
	 private DepartmentRepository departmentRepository;
	
	
	 @Override
	 public BaseResponse add(Department t) {
	    	
	    	BaseResponse  baseResponse=checkProperties(t);
	    	
	    	if(baseResponse.getStatus().intValue()==0) {
	    		return baseResponse;
	    	}
	    	
	    	long totalCount=departmentRepository.getCountByCode(t.getCode()); 
	    	
	      	if(totalCount>0L) {
	    		baseResponse.setFailed(DepartmentMessages.FAILED_MESSAGE_CODE_CAN_NOT_BE_DUPLICATE.getName());
	    		return baseResponse;
	    	}
	      	
	    	t.setCode(t.getCode().toUpperCase());
			if(!StringUtils.isEmpty(t.getNameEn())){
				t.setNameEn(t.getNameEn().toUpperCase());
			}

	    	
	    	departmentRepository.saveAndFlush(t);
			
			baseResponse.setSccucess(t);
			
			return baseResponse;
		}
	    
	    
	    @Override
	    public BaseResponse update(Department t) {
	   	 
	        BaseResponse  baseResponse=checkProperties(t);
	    	//校验不通过
	    	if(baseResponse.getStatus().intValue()==0) {
	    		return baseResponse;
	    	}
	    	
	    	long totalCount=departmentRepository.getCountByCodeAndExcludeId(t.getCode().toUpperCase(), t.getId()); 
	    	
	      	if(totalCount>0L) {
	    		baseResponse.setFailed(DepartmentMessages.FAILED_MESSAGE_CODE_CAN_NOT_BE_DUPLICATE.getName());
	    		return baseResponse;
	    	}
	    	
	      	Department old=departmentRepository.getOne(t.getId());
	    	
	    	if(old==null||old.getId().longValue()==0L) {
	    		baseResponse.setFailedForObjectNotExist();
	    		return baseResponse;
	    	}
	    	
	    	old.setNameZh(t.getNameZh());
			if(!StringUtils.isEmpty(t.getNameEn())){
				old.setNameEn(t.getNameEn().toUpperCase());
			}
			old.setSeqNum(t.getSeqNum());
			old.setCategory(t.getCategory());
			old.setCode(t.getCode().toUpperCase());
			old.setAddress(t.getAddress());
			old.setContactPerson(t.getContactPerson());
			old.setEmail(t.getEmail());
			old.setTelephone(t.getTelephone());
			old.setParentId(t.getParentId());
	    	
			departmentRepository.saveAndFlush(old);
			baseResponse.setSccucess(t);
			return baseResponse;
		}
		
	    @Override
	    @Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor=Exception.class)
	    public BaseResponse deleteById(Long id) {
			
			BaseResponse  baseResponse=new BaseResponse();
			
			Department old=departmentRepository.getOne(id);
			
			if(old==null||old.getId().longValue()==0L) {
	    		baseResponse.setFailedForObjectNotExist();
	    		return baseResponse;
	    	}
			
			long totalCount=departmentRepository.getCountByParentId(id);
			
			if(totalCount>0L) {
	    		baseResponse.setFailed(DepartmentMessages.FAILED_MESSAGE_EXIST_CHILDREN.getName());
	    		return baseResponse;
	    	}
			
			if(old.getUsers().size()>0){
				//解除用户与该部门的关联
				for (User user:old.getUsers()){
					user.setDepartment(null);
				}
			}
			
			departmentRepository.delete(old);
			
			baseResponse.setSccucess();
			
			return baseResponse;
		}
	    @Override
	    public BaseResponse getZTreeJSON(){
			List<Department> result=departmentRepository.findAll();
			List<DepartmentZtree> treeList=new ArrayList<DepartmentZtree>();
			for(int i=0;i<result.size();i++){
				Department t=(Department)result.get(i);
				DepartmentZtree tree=new DepartmentZtree();
				tree.setId(t.getId());
				tree.setpId(t.getParentId());
				tree.setName(t.getNameZh());
				tree.setNameEn(t.getNameEn());
				tree.setSeqNum(t.getSeqNum());
				tree.setCategory(t.getCategory());
				tree.setCode(t.getCode());
				tree.setAddress(t.getAddress());
				tree.setContactPerson(t.getContactPerson());
				tree.setEmail(t.getEmail());
				tree.setTelephone(t.getTelephone());
				tree.setNameZh(t.getNameZh());
				tree.setParentId(t.getParentId());
				treeList.add(tree);
			}
			BaseResponse resoponse=new BaseResponse();
			resoponse.setSccucess(treeList);
			return resoponse;
		}
	 
	  /**
	   * 检查属性
	   * @param t
	   * @return
	   */
	  private BaseResponse checkProperties (Department t) {
		  	 
			BaseResponse  baseResponse=new BaseResponse();
			    
		    if(StringUtils.isEmpty(t.getNameZh())) {
		    	baseResponse.setFailed(DepartmentMessages.FAILED_MESSAGE_NAME_ZH_CAN_NOT_BE_EMPTY.getName());
		    	return baseResponse;
		    }
		
		    if(StringUtils.isEmpty(t.getCode())) {
		    	baseResponse.setFailed(DepartmentMessages.FAILED_MESSAGE_CODE_CAN_NOT_BE_EMPTY.getName());
		    	return baseResponse;
		    }
		    if(t.getSeqNum()==null) {
		    	baseResponse.setFailed(DepartmentMessages.FAILED_MESSAGE_SEQ_NUM_CAN_NOT_BE_EMPTY.getName());
		    	return baseResponse;
		    }
		    baseResponse.setSccucess();
		    return baseResponse;
	   }

	

}
